Completed
Push — development ( ba4c0b...a5f65a )
by Nils
07:22
created

functions.js ➔ IsValidEmail   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
/**
2
 * @file          functions.js
3
 * @author        Nils Laumaillé
4
 * @version       2.1.27
5
 * @copyright     (c) 2009-2017 Nils Laumaillé
6
 * @licensing     GNU AFFERO GPL 3.0
7
 * @link          http://www.teampass.net
8
 *
9
 * This library is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
 */
13
14
/**
15
*   Show or hide Loading animation GIF
16
**/
17
function LoadingPage(){
18
    if ($("#div_loading").is(":visible")) {
19
        $("#div_loading").addClass("hidden");
20
    } else {
21
        $("#div_loading").removeClass("hidden");
22
    }
23
}
24
25
26
/**
27
*   Add 1 hour to session duration
28
**/
29
function IncreaseSessionTime(messageEnd, messageWait, duration){
30
    duration = duration || 60;
31
    $("#main_info_box_text").html(messageWait);
32
    $("#main_info_box").show().position({
33
        my: "center",
34
        at: "center top+75",
35
        of: "#top"
36
    });
37
    $.post(
38
        "sources/main.queries.php",
39
        {
40
        type    : "increase_session_time",
41
        duration: parseInt(duration) * 60
42
        },
43
        function(data){
44
            if (data[0].new_value !== "expired") {
45
                $("#main_info_box_text").html(messageEnd);
46
                $("#main_info_box").show(1).delay(3000).fadeOut(1000)
47
                $("#temps_restant").val(data[0].new_value);
48
                $("#date_end_session").val(data[0].new_value);
49
                $("#countdown").css("color","white");
50
                $("#div_increase_session_time").dialog("close");
51
            } else {
52
                $(location).attr('href',"index.php?session=expired");
53
            }
54
        },
55
        "json"
56
    );
57
}
58
59
/**
60
*   Countdown before session expiration
61
**/
62
function countdown()
63
{
64
    var DayTill;
65
    var theDay =  $("#temps_restant").val();
66
    var today = new Date(); //Create an Date Object that contains today's date.
67
    var second = Math.floor(theDay - (today.getTime()/1000));
68
    var minute = Math.floor(second/60); //Devide "second" into 60 to get the minute
69
    var hour = Math.floor(minute/60); //Devide "minute" into 60 to get the hour
70
    var CHour= hour % 24; //Correct hour, after devide into 24, the remainder deposits here.
71
    if (CHour<10) {
72
        CHour = "0" + CHour;
73
    }
74
    var CMinute= minute % 60; //Correct minute, after devide into 60, the remainder deposits here.
75
    if (CMinute<10) {
76
        CMinute = "0" + CMinute;
77
    }
78
    var CSecond= second % 60; //Correct second, after devide into 60, the remainder deposits here.
79
    if (CSecond<10) {
80
        CSecond = "0" + CSecond;
81
    }
82
    DayTill = CHour+":"+CMinute+":"+CSecond;
83
84
    //Avertir de la fin imminante de la session
85
    if (DayTill === "00:01:00") {
86
        $("#div_increase_session_time").dialog("open");
87
        $("#countdown").css("color","red");
88
    }
89
90
    // Manage end of session
91
    if ($("#temps_restant").val() !== "" && DayTill <= "00:00:00" && $("#please_login").val() !== "1") {
92
        $("#please_login").val("1");
93
        $(location).attr('href',"index.php?session=expired");
94
    }
95
96
    //Rewrite the string to the correct information.
97
    if ($("#countdown")) {
98
        $("#countdown").html(DayTill); //Make the particular form chart become "Daytill"
99
    }
100
101
    //Create the timer "counter" that will automatic restart function countdown() again every second.
102
    $(this).delay(1000).queue(function() {
103
        countdown();
104
        $(this).dequeue();
105
    });
106
}
107
108
/**
109
*   Open a dialog
110
**/
111
function OpenDialog(id){
112
    $("#"+id).dialog("open");
113
}
114
115
/**
116
*   Toggle a DIV
117
**/
118
function toggleDiv(id){
119
    $("#"+id).slideToggle("slow");
120
    //specific case to not show upgrade alert
121
    if(id === "div_maintenance"){
122
        $.post(
123
            "sources/main.queries.php",
124
            {
125
                type    : "hide_maintenance"
126
            }
127
        );
128
    }
129
}
130
131
/**
132
*   Checks if value is an integer
133
**/
134
function isInteger(s) {
135
  return (s.toString().search(/^-?[0-9]+$/) === 0);
136
}
137
138
/**
139
*   Generate a random string
140
**/
141
function CreateRandomString(size,type){
142
    var chars = "";
143
144
    // CHoose what kind of string we want
145
    if (type === "num") {
146
        chars = "0123456789";
147
    } else if (type === "num_no_0") {
148
        chars = "123456789";
149
    } else if (type === "alpha") {
150
        chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
151
    } else if (type === "secure") {
152
        chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz&#@;!+-$*%";
153
    } else {
154
        chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
155
    }
156
157
    //generate it
158
    var randomstring = "";
159
    for (var i=0; i<size; i++) {
160
        var rnum = Math.floor(Math.random() * chars.length);
161
        randomstring += chars.substring(rnum,rnum+1);
162
    }
163
164
    //return
165
    return randomstring;
166
}
167
168
169
/**
170
*
171
**/
172
function unsanitizeString(string){
173
    if(string !== "" && string !== null && string !== undefined){
174
        string = string.replace(/\\/g,"").replace(/&#92;/g,"\\");
175
    }
176
    return string;
177
}
178
179
/**
180
*   Clean up a string and delete any scripting tags
181
**/
182
function sanitizeString(string){
183
    if(string !== "" && string !== null && string !== undefined) {
184
        string = string.replace(/\\/g,"&#92;").replace(/"/g,"&quot;");
185
        string = string.replace(new RegExp("\\s*<script[^>]*>[\\s\\S]*?</script>\\s*","ig"), "");
186
    }
187
    return string;
188
}
189
190
/**
191
*   Send email
192
**/
193
function SendMail(category, contentEmail, keySent, message){
194
    $.post(
195
        "sources/items.queries.php",
196
        {
197
            type    : "send_email",
198
            cat     : category,
199
            content : contentEmail,
200
            key     : keySent
201
        },
202
        function(data){
203
            if (typeof data[0].error !== "undefined" && data[0].error !== "") {
204
                message = data[0].message;
205
            }
206
            $("#div_dialog_message_text").html(message);
207
            $("#div_dialog_message").dialog("open");
208
        },
209
        "json"
210
    );
211
}
212
213
/**
214
*   Checks if email has expected format ([email protected])
215
**/
216
function IsValidEmail(email){
217
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
218
    return filter.test(email);
219
}
220
221
/**
222
*   Checks if URL has expected format
223
**/
224
function validateURL(textval) {
225
    //var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
226
    var urlregex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
227
    return urlregex.test(textval);
228
}
229
230
231
function split( val ) {
232
    return val.split( / \s*/ );
233
}
234
235
function extractLast( term ) {
236
    return split( term ).pop();
237
}
238
239
240
function storeError(messageError, dialogDiv, textDiv){
241
    //Store error in DB
242
    $.post(
243
        "sources/main.queries.php",
244
        {
245
            type    : "store_error",
246
            error   : escape(messageError)
247
        }
248
    );
249
    //Display
250
    $("#"+textDiv).html("An error appears. Answer from Server cannot be parsed!<br />Returned data:<br />"+messageError);
251
    $("#"+dialogDiv).dialog("open");
252
}
253
254
/**
255
 * [aesEncrypt description]
256
 * @param  {[type]} text [description]
257
 * @param  {[type]} key  [description]
258
 * @return {[type]}      [description]
259
 */
260
function aesEncrypt(text, key)
261
{
262
    return Aes.Ctr.encrypt(text, key, 256);
263
}
264
265
/**
266
 * [aesDecrypt description]
267
 * @param  {[type]} text [description]
268
 * @param  {[type]} key  [description]
269
 * @return {[type]}      [description]
270
 */
271
function aesDecrypt(text, key)
272
{
273
    return Aes.Ctr.decrypt(text, key, 256);
274
}
275
276
/**
277
 * Shows error message
278
 * @param  {string} message  Message to display
279
 * @return {boolean}         False
280
 */
281
function jsonErrorHdl(message)
282
{
283
    $("#div_dialog_message_text").html(message);
284
    $("#div_dialog_message").dialog("open");
285
    $("#items_path_var").html('<i class="fa fa-folder-open-o"></i>&nbsp;Error');
286
    $("#items_list_loader").addClass("hidden");
287
    return false;
288
}
289
290
/**
291
 * [prepareExchangedData description]
292
 * @param  {[type]} data [description]
293
 * @param  {[type]} type [description]
294
 * @param  {[type]} key  [description]
295
 * @return {[type]}      [description]
296
 */
297
function prepareExchangedData(data, type, key)
298
{
299
    var jsonResult;
0 ignored issues
show
Unused Code introduced by
The variable jsonResult seems to be never used. Consider removing it.
Loading history...
300
    if (type === "decode") {
301
        if ($("#encryptClientServer").val() === "0") {
302
            try {
303
                return $.parseJSON(data);
304
            }
305
            catch (e) {
306
                return "Error: " + jsonErrorHdl(e);
307
            }
308
        } else {
309
            try {
310
                return $.parseJSON(aesDecrypt(data, key));
311
            }
312
            catch (e) {
313
                return "Error: " + jsonErrorHdl(e);
314
            }
315
        }
316
    } else if (type === "encode") {
317
        if ($("#encryptClientServer").val() === "0") {
318
            return data;
319
        } else {
320
            return aesEncrypt(data, key);
321
        }
322
    } else {
323
        return false;
324
    }
325
}
326
327
/**
328
 * Show a message to the user on top of the screen
329
 * @param  {[type]} textToDisplay [description]
330
 * @return {[type]}               [description]
331
 */
332
function displayMessage(textToDisplay)
333
{
334
    $("#main_info_box_text").html(textToDisplay);
335
    $("#main_info_box").show().position({
336
        my: "center",
337
        at: "center top+20",
338
        of: "#main_simple"
339
    });
340
    $(this).delay(2000).queue(function() {
341
        $("#main_info_box").effect( "fade", "slow");
342
        $(this).dequeue();
343
    });
344
}
345
346
/**
347
 * Make blinking an HMLT element
348
 * @param  {[type]} elem  [description]
349
 * @param  {[type]} times [description]
350
 * @param  {[type]} speed [description]
351
 * @param  {[type]} klass [description]
352
 * @return {[type]}       [description]
353
 */
354
function blink(elem, times, speed, klass)
355
{
356
    if (times > 0 || times < 0) {
357
        if ($(elem).hasClass(klass)) {
358
            $(elem).removeClass(klass);
359
        } else {
360
            $(elem).addClass(klass);
361
        }
362
    }
363
364
    clearTimeout(function() { blink(elem, times, speed, klass); });
365
366
    if (times > 0 || times < 0) {
367
        $(this).delay(speed).queue(function() {
368
            blink(elem, times, speed, klass);
369
            $(this).dequeue();
370
        });
371
        times-= .5;
372
    }
373
}